package com.blankii.androidlibrary.lib.version

import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.Buffer
import okio.BufferedSource
import okio.ForwardingSource
import okio.Okio
import okio.Source
import java.io.IOException


/**
 * author: blankii
 * created on: 2024/4/19 15:21
 * description:
 */

class ProgressResponseBody(
    responseBody: ResponseBody?,
    progressListener: ProgressListener
) :
    ResponseBody() {
    private val responseBody: ResponseBody?
    private val progressListener: ProgressListener
    private var bufferedSource: BufferedSource? = null

    init {
        this.responseBody = responseBody
        this.progressListener = progressListener
    }

    override fun contentType(): MediaType? {
        return responseBody!!.contentType()
    }

    override fun contentLength(): Long {
        return responseBody!!.contentLength()
    }

    override fun source(): BufferedSource? {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(source(responseBody!!.source()))
        }
        return bufferedSource
    }

    private fun source(source: Source): Source {
        return object : ForwardingSource(source) {
            var totalBytesRead = 0L

            @Throws(IOException::class)
            override fun read(sink: Buffer?, byteCount: Long): Long {
                val bytesRead = super.read(sink, byteCount)
                totalBytesRead += if (bytesRead != -1L) bytesRead else 0
                progressListener.update(
                    totalBytesRead,
                    responseBody!!.contentLength(),
                    bytesRead == -1L
                )
                return bytesRead
            }
        }
    }
}
